package com.mymarkdown.app.common.itext;

import com.itextpdf.io.util.ResourceUtil;
import com.itextpdf.io.util.StreamUtil;
import com.itextpdf.layout.font.FontProvider;
import com.mymarkdown.app.common.constant.Constant;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author zenglun
 * @date 2021/12/8 1:54 下午
 * @description: 自定义中文字体库
 */
public class ChineseFontProvider extends FontProvider {
    private static final String SHIPPED_FONT_RESOURCE_PATH = "com/itextpdf/html2pdf/font/";

    private static final String[] SHIPPED_FONT_NAMES = new String[]{"FreeMono.ttf", "FreeMonoBold.ttf", "FreeMonoBoldOblique.ttf", "FreeMonoOblique.ttf", "FreeSans.ttf", "FreeSansBold.ttf", "FreeSansBoldOblique.ttf", "FreeSansOblique.ttf",
            "FreeSerif.ttf", "FreeSerifBold.ttf", "FreeSerifBoldItalic.ttf", "FreeSerifItalic.ttf"};

    public ChineseFontProvider() {
        this(true, true, false);
    }

    public ChineseFontProvider(boolean registerStandardPdfFonts, boolean registerShippedFreeFonts, boolean registerSystemFonts) {
        if (registerStandardPdfFonts) {
            this.addStandardPdfFonts();
        }

        if (registerShippedFreeFonts) {
            this.addShippedFreeFonts();
        }

        if (registerSystemFonts) {
            this.addSystemFonts();
        }

    }

    private void addShippedFreeFonts() {
        String[] shippedFontNames = SHIPPED_FONT_NAMES;
        int length = shippedFontNames.length;

        for (int i = 0; i < length; i++) {
            String fontName = shippedFontNames[i];
            InputStream stream = ResourceUtil.getResourceStream(SHIPPED_FONT_RESOURCE_PATH + fontName);

            try {
                byte[] fontProgramBytes = StreamUtil.inputStreamToArray(stream);
                this.addFont(fontProgramBytes);
            } catch (Exception e) {
            }
        }
        try {
            byte[] bytes = StreamUtil.inputStreamToArray(new FileInputStream(Constant.CHINES_FONT_PATH));
            this.addFont(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
